import type { DictItem } from '/#/store';
import { defineStore } from 'pinia';
import { store } from '/@/store';
import { DICTS_KEY } from '/@/enums/cacheEnum';
import { getAuthCache, setAuthCache } from '/@/utils/auth';
import { getDictList } from '/@/api/system/system';
import { isArray } from '/@/utils/is';

interface DictState {
  dictData: Map<string, DictItem[]>;
}

export const useDictStore = defineStore({
  id: 'app-dict',
  state: (): DictState => ({
    dictData: new Map<string, DictItem[]>(),
  }),
  getters: {
    getDictItems(): Map<string, DictItem[]> {
      return this.dictData.size > 0
        ? this.dictData
        : getAuthCache<Map<string, DictItem[]>>(DICTS_KEY);
    },
  },
  actions: {
    setDictData(dictData: Map<string, DictItem[]>) {
      this.dictData = dictData;
      setAuthCache(DICTS_KEY, dictData);
    },
    resetState() {
      this.dictData = new Map<string, DictItem[]>();
    },
    /**
     * @description: loadDictItems
     */
    async loadDictItems(): Promise<Map<string, DictItem[]> | null> {
      const dictArray = await getDictList({});
      // 设置数据
      const dictItemMap = new Map<string, DictItem[]>();
      if (isArray(dictArray)) {
        dictArray.forEach((dict) => {
          // 获得 dictType 层级
          const enumValueObj = dictItemMap.get(dict.dictCode);
          if (!enumValueObj) {
            dictItemMap.set(dict.dictCode, new Array<DictItem>());
          }
          // 服务端加载的字典数据值为string类型，如有必要则转换value类型
          let value = dict.value;
          if (dict.valueType === 'number') {
            value = Number(dict.value);
          }
          // 处理 dictValue 层级
          dictItemMap.get(dict.dictCode)?.push({
            value: value,
            label: dict.label,
            color: dict.color,
          });
        });
      }
      this.setDictData(dictItemMap);
      return dictItemMap;
    },
  },
});

// Need to be used outside the setup
export function useDictStoreWithOut() {
  return useDictStore(store);
}
